繁体   English   中英

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

[英]join two tables and pick one row from the second table if a field is set in second table otherwise select any row

我在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的图像中选择一行,否则它可以从连接到adverts表的图像中选择任何行。 编辑:在表格图像中有4或5行。 仅将0或1行设置为1。因此,如果default_img设置为1,则最后一行将包含adverts表中的某些列与imagess表中的行连接,否则,将选择与default_img =对应的任何广告行0。 先谢谢您的帮助。

我对吗:

如果default_img =='1',则要获取图像行

select * from images where default_img='1'

否则,您想获取id为adverts_id的adverts行吗?

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'

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

按照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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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