tags:

views:

104

answers:

2
SELECT * FROM tbl_houses 
WHERE 
 (SELECT HousesList 
  FROM tbl_lists 
  WHERE tbl_lists.ID = '123') LIKE CONCAT('% ', tbl_houses.ID, '#')

It only selects the row from tbl_houses of the last occuring tbl_houses.ID inside tbl_lists.HousesList

I need it to select all the rows where any ID from tbl_houses exists within tbl_lists.HousesList

A: 

Is that a database in zeroth normal form I smell?

If you have attributes containing lists of values, like that HousesList attribute, you should instead be storing those as distinct values in a separate relation.

CREATE TABLE house (
    id VARCHAR NOT NULL,
    PRIMARY KEY (id)
    );

CREATE TABLE list (
    id VARCHAR NOT NULL,
    PRIMARY KEY (id),
    );

CREATE TABLE listitem (
    list_id VARCHAR NOT NULL,
        FOREIGN KEY list_id REFERENCES list (id),
    house_id VARCHAR NOT NULL,
        FOREIGN KEY house_id REFERENCES house (id),
    PRIMARY KEY (list_id, house_id)
    );

Then your distinct house listing values each have their own tuple, and can be selected like any other.

SELECT house.*
FROM house
    JOIN listitem
        ON listitem.house_id = house.id
WHERE
    listitem.list_id = '123'
bignose
I have my reasons for storing specific data in this way. "Houses" and "ID"s aren't related to my actual project. I'm just giving an example of the query that is for some reason, only returning the first record.
Joe
Nevertheless, your problem as described is very much tied to the fact that you have unnormalised data, and are trying to fight against the relational nature of the database system.
bignose
The problem was solved. No need to change any structure. But YES, definately need to have better coding practices I understand that. If you knew my project I think you would agree with my method, though, considering the alternative is ridiculous.
Joe
+2  A: 

It's hard to tell without knowing exactly what your data looks like, but if it only matches the last ID, it's probably because you don't have any % at the end of the string, so as to allow for the list to continue after the match.

David Hedlund
Data looks like this: 1# 4# 41# 32# 4134# 94#There is a space before each ID. Each ID ends with #.
Joe
yes, but your `LIKE` does not end with a `%`, so it says that the match *must end* with what you've searched for. That could be true for `94#`, but it won't be true for `4134#` since the string doesn't end there. change to: `LIKE CONCAT('% ', tbl_houses.ID, '#%')`
David Hedlund
Eureka... I think you got it! DEFINATELY you got it!! Thanks... smart guy you are!
Joe