如果另一个表中不存在连接字段值,则从JOIN查询获取默认值

时间:2018-01-25 06:18:12

标签: mysql

我有两张表customersreviews。结构是这样的:

客户: -

|---------------------------------|
|  id  |         name             |
|---------------------------------|
|   1  |       Thutmekri          |
|---------------------------------|
|   3  |        Conan             |
|---------------------------------|

评论: -

|-------------------------------------------|
|   id   |   business_id  |    customer_id  |
|-------------------------------------------|
|   1    |       1        |        1        |
|-------------------------------------------|
|   2    |       1        |        2        |
|-------------------------------------------|
|   3    |       1        |        3        |
|-------------------------------------------|
customer_id的{​​p> reviewsid的{​​{1}}。

联接查询,

customer

返回如下数据集: -

SELECT customers.name, reviews.id as review_id 
FROM customers, reviews 
WHERE customers.id = reviews.customer_id

但我想要它返回: -

|----------------------------------|
|    review_id  |      name        |
|----------------------------------|
|       1       |      Thutmekri   |
|----------------------------------|
|       3       |      Conan       |
|----------------------------------|

对于评论中的customer_id,在customers表中没有任何数据,我希望显示“N / A”。我该怎么办?

以下查询也没有帮助

|----------------------------------|
|    review_id  |      name        |
|----------------------------------|
|       1       |      Thutmekri   |
|----------------------------------|
|       2       |      N/A         |
|----------------------------------|
|       3       |      Conan       |
|----------------------------------|

4 个答案:

答案 0 :(得分:1)

使用左连接并切换连接中表格的顺序:

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/recylerview"></android.support.v7.widget.RecyclerView>

SQLFiddle

答案 1 :(得分:0)

试试这个:

SELECT r.id  as review_id, COALESCE( c.name, 'N/A' ) FROM reviews r
LEFT JOIN customers c ON c.id = r.customer_id

答案 2 :(得分:0)

使用右外连接来实现此目的:

SELECT
    reviews.id as review_id,
    COALESCE(name, 'N/A' )
FROM customers
RIGHT JOIN reviews
    ON customers.id = reviews.customer_id;

答案 3 :(得分:0)

您可以使用以下查询

选择      R.id AS review_id,      COALESCE(C.name,'N / A')AS名称来自评论R LEFT JOIN客户C ON R.customer_id = C.id;