What I want to do is join the same table and see if the field "reference_id" has a value, if it does then it should use that value to get the actual row with data and use that data for the rest of the query - where and sort clauses, otherwise use the original entries data.
Table "entries" fields:
id, text, type, reference_id, num_count
Example data:
[1, "", 0, 2, 0],
[2, "some text", 2, 0, 50],
[3, "more text", 2, 0, 60],
Should return:
row 0: "more text"
row 1: "some text"
The query looks something like this:
SELECT entries.text
FROM entries
LEFT JOIN entries as e2
ON entries.reference_id = e2.id
WHERE type = $type
ORDER BY num_count DESC
So the last two clauses should change from entries.type
and entries.num_count
to e2.type
and e2.num_count
if reference_id has something. How do I achieve this?
Please write with alias in where clause
SELECT entries.text
FROM entries
LEFT JOIN entries as e2
ON entries.reference_id = e2.id
WHERE entries.type = $type
ORDER BY entries.num_count DESC
If I understand correctly then you just want to use the left joined table values if they exist, otherwise the main tables values.
I so something like this:-
SELECT COALESCE(e2.text, entries.text)
FROM entries
LEFT OUTER JOIN entries as e2
ON entries.reference_id = e2.id
WHERE type = $type
ORDER BY COALESCE(e2.num_count, entries.num_count) DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.