问题
i have two tables called musical_types and musical_albums in which musical_types consists of type_name and an auto increment id, where as in the musical_albums table contains auto increment id , name , types which is a varchar which stores the id of musical_types as comma seperated values like 1,2,3,4 etc. So could anyone please help me in getting all the albums of type x from musical_albums table.
I tried mysql like but it is not correct. so please help me in writing this query..
iam using codeigniter, is it possible to write the above mentioned query in codeigniters active record class.
another point is this is a joomla component table design, and iam writing a script for an android webservice that returns the musical events, songs etc..
Thanks in advance.
回答1:
Try this one but @juergen already mentioned do not store values as comma separated it results in a pain for now you can do as below
$this->db->select('*');
$this->db->from('musical_albums');
//$this->db->join('second table name', 'relation id of 1st table = relation id of 2nd table');
//Custom string: in where
$where = " FIND_IN_SET('x',`types`)";
$this->db->where($where);
$query = $this->db->get();
Active Record
FIND_IN_SET()
回答2:
Never, never, never store multiple values in one column!
Like you see now this will only give you headaches. Normalize your table. Then you can join normally.
回答3:
You have what is refereed to as a many-to-many relationship between your types data and albums data. As @juergen mentioned, attempting to store multiple values in one column like you're doing is incorrect. A quick Google search will get you lots of info for what you need, but basically you'll want a third 'mapping' table that simply maps together albums and their types.
来源:https://stackoverflow.com/questions/18816116/where-condition-from-a-comma-seperated-varchar-in-mysql-and-codeigniter