简体   繁体   中英

Mysql searching and sorting in one query with joined tables

I have 3 tables in Mysql 5.

Table Client: ID, Username, Password.
Table Client_Data: ID, Dataname
Table Client_Client_Data: client_id, Data_id, Value

The idea is that I can have the user of this software determine which information he wants to get from his clients. The Client_Data table would typically be filled with "First Name", "Last Name", "Address" and so on. The third table will join the tables together. An example:

Client: ID=1 Username=Bert01 Password=92382938v2nvn239
Client_Data: ID=1 Dataname=First Name
Client_Client_Data: client_id=1 data_id=1 value=Bert

This would mean that Bert01 has a first name "Bert" when joining the tables in a select query.

I'm displaying all this in a table where the columns are the DataName values (if you lost me here: the headers would be like "First Name", "Last Name" and so on). I want to be able to sort this data alphabetically for each column.

My solution was to use 2 queries. The first one would collect the data with WHERE Client_Data.Dataname = $sortBy ORDER BY Client_Client_Data.value and the second query would then collect the other data with WHERE Client.ID = 1 OR 2 OR 3 containing all of the ID's collected in the first query. This is working great.

The problem that has been playing in my mind for a long time now is when I want to search my data. This would not be too hard if it weren't for the sorting. After the search has been done the table would contain the results, but this table has to be sorted the same way as before.

Does anyone have any idea on how to do this without bothering the webserver's memory by looping through potentially thousands of clients? (meaning: i want to do this in Mysql).

If your solution would require altering the tables without losing the capability of storing this kind of data: that would be no problem.

you could relocate the looping. make a select from all the datatypes

Select * from Client_Data

then use that info to build a query like so (psuedo code)

orderby = "name"
query = "select *"
foreach(datatypes as dt){
 query += ",(select d.value from Client_Client_Data as d where d.data_id="+dt.ID+" and d.client_id=cl.ID) as "+dt.Dataname
}
query = "from Client as cl order by "+orderby;

this will result in a table with all the available datatypes transfered into a column and the corresponding value connected to the correct client trough d.client_id=cl.ID

whereas cl.ID refers to the main queries client id and matches it against Client_Client_Data.client_id

now beware i am not entirely sure about the subqueries being more efficient. would require some testing

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM