I have this table:
id | word1 | word2
1 | 100 | 200
2 | 101 | 200
I want to show the word_number
values only one time, for example, for the current table - here`s my expected result:
100, 101, 200
I have tried this:
$stmt = $mysqli->prepare('SELECT word1, word2 FROM table GROUP BY word1, word2 ORDER BY id DESC LIMIT ?, ?');
$stmt->bind_param('ii', $start,$perpage);
$stmt->execute();
in this way its group only the word1, so the result its:
100, 200, 101, 200
When I change the GROUP BY
to word2
its correct, but its to opposite.
id | word1 | word2
1 | 100 | 200
2 | 101 | 200
for this table, id
row its primary key, its mean grow every row. so for word1 = 100, word2 = 200 - the id
value its 1
- I want to ORDER BY
this id
key.
If you don't really need the result to be sorted by the ID?
Then you could use a normal UNION
with a select for both word fields.
A normal UNION
already discards duplicates, so it won't need a GROUP BY
then.
$stmt = $mysqli->prepare('SELECT word1 as word FROM table UNION SELECT word2 FROM table ORDER BY word DESC LIMIT ?, ?');
And if it does need to be sorted by the ID, then using a UNION ALL
wouldn't remove the dups. So you can group & sort from a sub-query.
Then the Query could be something like this:
SELECT word
FROM
(
SELECT id, word1 as word
FROM table
UNION ALL
SELECT id, word2
FROM table
) q
GROUP BY word
ORDER BY MAX(id) DESC
LIMIT ?, ?
Or by using the CROSS JOIN
to numbers trick.
select case n when 1 then word1 when 2 then word2 end as word
from table
cross join (select 1 n union all select 2) N
group by word
order by min(id) desc
limit ?, ?