SQL JOIN有条件

时间:2016-08-08 07:41:29

标签: mysql sql

我有一个conversation表,其中包含两个用户ID作为外键,以及包含用户详细信息的用户表。我想编写一个查询,该查询返回加入用户表的conversation表,但显示其id未作为参数发送的用户的姓名和姓氏。

CREATE TABLE `conversation` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_one_id` int(11) NOT NULL,
  `user_two_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `surname` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
)

例如我有

会话

id      user_one_id      user_two_id
1       1                2

用户:

id       name            surname
1        userone_name    userone_surname
2        usertwo_name    usertwo_surname

我想要一个查询,它将在联接中返回user_two的名称和姓氏,而不是用户1。 我目前的查询:

SELECT c.id, c.user_one_id, c.user_two_id, u.name, u.surname * FROM conversation c
        JOIN user u
        WHERE c.user_one_id = 1
        OR c.user_two_id = 1
        AND IF (c.user_one_id = u.id, c.user_two_id = u.id, c.user_one_id = u.id)
        GROUP BY c.id
        ORDER BY c.date DESC;

1 个答案:

答案 0 :(得分:4)

ON应该有一个SELECT c.id, c.user_one_id, c.user_two_id, u.name, u.surname FROM conversation c JOIN user u ON u.id IN (c.user_one_id, c.user_two_id) AND u.id <> 1 WHERE c.user_one_id = 1 OR c.user_two_id = 1 ORDER BY c.date DESC; 子句。 (我认为MySQL允许你省略它是一个缺陷。)

加入条件必须是:向我提供非用户1的对话的用户。

<?php
/*
Plugin Name: Modify Klarna Checkout URL
Plugin URI: http://krokedil.com
Description: Change checkout URL for Klarna Checkout if user isn't from a specific country
Version: 1.0
Author: Krokedil
Author URI: http://krokedil.com
*/
add_filter( 'woocommerce_get_checkout_url', 'krokedil_change_checkout_url', 30 );
function krokedil_change_checkout_url( $url ) {
    $allowed_countries = array('NO');
    $customer_country = WC()->customer->get_default_country();
    if( !in_array( $customer_country , $allowed_countries ) ) {
        $url = wc_get_page_permalink( 'checkout' );
    }
    return $url;
}