Bolli Bolli - 5 months ago 9
SQL Question

Grouping/joining columns in Mysql

UPDATE

I solved it my self using:
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_concat-ws

I updated the code below if anyone need to do the same and lands here.

I have a small MySQL database where I'm Searching for users

SELECT *, kunde.id as kundeid
FROM kunde
INNER JOIN $bartype ON ($bartype.brugerid = kunde.id)
WHERE $bartype.barid ='$barid[Barid]' AND
(email LIKE '%$keyword%') OR
(fornavn LIKE '%$keyword%') OR
(efternavn LIKE '%$keyword%') OR
(CONCAT_WS(' ', fornavn, efternavn) LIKE '%$keyword%')
LIMIT 0, 50;


Now my search function works, but only for either
'%$keyword%' LIKE fornavn or '%$keyword%' LIKE efternavn or '%$keyword%' LIKE email
.

So I would like to group the LIKE results so that when searching for "fornavn efternavn" in one string it would still show up results from these 2 columns that are in the same row.

Does this make sense? And is it possible to modify my SQL statement to do this?

Thanks in advanced.

Answer

To do what you would like, you might want to try a UNION statement. A union statement will take results from one query and add it into the results from another query while preserving the order (in my example, results having the email will come first, followed by fornavn, followed by efternavn). Doing it this way will also eliminate your AND/OR logic that might be preventing search results from appearing.

SELECT *, kunde.id as kundeid
FROM kunde
INNER JOIN $bartype ON ($bartype.brugerid = kunde.id)
WHERE  $bartype.barid ='$barid[Barid]' AND
    email LIKE '%$keyword%'
UNION ALL
SELECT *, kunde.id as kundeid
FROM kunde
INNER JOIN $bartype ON ($bartype.brugerid = kunde.id)
WHERE  $bartype.barid ='$barid[Barid]' AND
    fornavn LIKE '%$keyword%'
UNION ALL
SELECT *, kunde.id as kundeid
FROM kunde
INNER JOIN $bartype ON ($bartype.brugerid = kunde.id)
WHERE  $bartype.barid ='$barid[Barid]' AND
    efternavn LIKE '%$keyword%'

On a side note, dynamic SQL like this is ripe for SQL injection. May I suggest you to look into PHP PDO

UPDATE

After your comment, here is an updated query that may be able to perform both searches at once for you:

SELECT *, kunde.id as kundeid
FROM kunde
INNER JOIN $bartype ON ($bartype.brugerid = kunde.id)
WHERE  $bartype.barid ='$barid[Barid]' AND
    email LIKE '%$keyword%'
UNION ALL
SELECT *, kunde.id as kundeid
FROM kunde
INNER JOIN $bartype ON ($bartype.brugerid = kunde.id)
WHERE  $bartype.barid ='$barid[Barid]' AND
    fornavn + ' ' + efternavn LIKE '%$keyword%'
Comments