Home > database >  SQL - Ordering table with subquery for select
SQL - Ordering table with subquery for select

Time:01-19

I am trying to do ordering on query with subquery for a name from uuid. Let's have those two tables in MySQL:

bans:

id uuid time reason
1 c6b8eade-7db9-345b-b838-8f8361552cf5 1642369382 Test
2 0138c279-c5fa-3acd-adaa-8edb7b4569d8 1642384565 Spam
3 3c01262c-a3c3-3133-ba43-92a9ded01c27 1631876477 Hax

users:

id uuid name
45 c6b8eade-7db9-345b-b838-8f8361552cf5 John
100 0138c279-c5fa-3acd-adaa-8edb7b4569d8 Mike
35 3c01262c-a3c3-3133-ba43-92a9ded01c27 Norman

With this query, I can select whole ban record fetch user's name from users table:

SELECT
    bans.*,
    (SELECT users.name FROM users WHERE users.uuid = bans.uuid) as name
FROM bans
ORDER BY :column;

But I cannot order by name. How to change this query so I can do ordering by users.name? I tried to wrap my SQL select into another select, but it does not work and I am unable to resolve it :D

CodePudding user response:

That is a JOIN query if I ever saw one.

You cannot pass a table or column name as a parameter in either PDO or MYSQLI. The database cannot compile and optimise code with unknown columns or tables in it

SELECT b.*, u.name
FROM bans b
    LEFT JOIN users u ON u.uuid = b.uuid
ORDER BY u.name;

CodePudding user response:

maybe you can try this

select a.id, a.uuid, a.time, a.reason, b.name from bans a
left join users b
on a.uuid = b.uuid
order by b.name;

CodePudding user response:

You cannot use parameterize identifier (database/table/column/etc) names. Your database library is most likely transforming this:

SELECT * FROM t ORDER BY :column

Into this:

SELECT * FROM t ORDER BY 'name'

It is perfectly valid SQL as far as MySQL is concerned, yet it won't produce the expected result since it is ordering by a constant. You need to explicitly specify the column name:

ORDER BY name
  •  Tags:  
  • Related