簡體   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