如果在第二个表中设置了字段,则连接两个表并从第二个表中选择一行,否则选择任何行

时间:2014-06-11 09:38:34

标签: sql sqlite join

我在sqlite中有两个表 -

CREATE TABLE adverts ( 
    _id            INTEGER PRIMARY KEY,
    title          TEXT,
    created_date   TEXT,
    details        TEXT,
    price          TEXT,
    codition       TEXT,
    phone          TEXT,
    alt_phone      TEXT,
    address        INTEGER,
    expiry_date    TEXT,
    ad_serial      TEXT,
    active         INTEGER,
    users_id       INTEGER,
    type_id        INTEGER,
    area_id        INTEGER,
    city_id        INTEGER,
    subCategory_id INTEGER,
    bestDeals      TEXT,
    wanted         TEXT,
    category_id    INTEGER,
    hits           TEXT,
    check_date     TEXT,
    u_email        TEXT,
    ip_address     TEXT,
    active_status  TEXT,
    premium        TEXT,
    language       TEXT,
    updated_by     TEXT,
    staff_note     TEXT,
    FOREIGN KEY ( users_id ) REFERENCES users ( _id ),
    FOREIGN KEY ( type_id ) REFERENCES type ( _id ),
    FOREIGN KEY ( area_id ) REFERENCES area ( _id ),
    FOREIGN KEY ( city_id ) REFERENCES city ( _id ),
    FOREIGN KEY ( subCategory_id ) REFERENCES subcategory ( _id ),
    FOREIGN KEY ( category_id ) REFERENCES category ( _id ) 
);

CREATE TABLE images ( 
    _id         INTEGER PRIMARY KEY,
    name        TEXT,
    path        TEXT,
    adverts_id  INTEGER,
    default_img TEXT,
    FOREIGN KEY ( adverts_id ) REFERENCES adverts ( _id ) 
);

我需要编写一个查询,选择连接两个表的数据,这两个表选择一行,其中default_img设置为1的图像行,否则它可以从连接到广告表的图像中选择任何行。 编辑:表格图像中有4或5行。只有0或1行将设置为1.因此,如果default_img设置为1,则最终行将包含广告表中连接到images表中行的一些列,否则它将使用default_img =选择与广告对应的任何行0。 在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我是对的:

如果default_img =='1'

,您想要获取图像行
select * from images where default_img='1'

否则你想获得id为adverts_id的广告行?

select * from images,adverts where images.adverts_id=adverts._id and images.default_img<>'1'

制作这一个命令:

select name,path,details from images,adverts where images.adverts_id=adverts._id and images.default_img<>'1'
union
select name,path,null from images where default_img='1'

您应该在最终代码中指定确切的列,但不能指定“*”。

答案 1 :(得分:0)

按照brummfondel的回答,我将查询更改为

select distinct adverts._id as _id, adverts.subCategory_id as subcategory_id, adverts.title as title, adverts.price as price, images.name as name, adverts.created_date as date from images,adverts where images.adverts_id=adverts._id and images.adverts_id not in(select images.adverts_id from images where images.default_img='1') group by adverts._id
union
select adverts._id as _id, adverts.subCategory_id as subcategory_id, adverts.title as title, adverts.price as price, images.name as name, adverts.created_date as date from images,adverts where images.adverts_id=adverts._id and default_img='1'
order by date

给了我想要的结果。 谢谢brummfondel。