左连接OR子句

时间:2017-03-05 10:44:15

标签: mysql left-join

我有2个表格,简化如下:

Table 1: | id | somedata | checkcode
Table 2: | id | somedata | checkcode1 | checkcode2

我需要离开加入第二个,其中checkcode1或checkcode2就像checkcode。我试图制作两个不同的左连接,但这不起作用,因为它包含了两倍的数据。

我需要的是这样的事情:

Select * from Table1 as t1     
LEFT JOIN Table2 as t2 
on t1.checkcode = (t2.checkcode1 OR t2.checkcode2)     

这可能吗?

4 个答案:

答案 0 :(得分:2)

试试这个,

public class TestFrag extends Fragment {
    private static final String[] phoneProjection = new String[]{ContactsContract.CommonDataKinds.Phone.DATA};
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.testfrag, container, false);

        TextView textView = (TextView) view.findViewById(R.id.clickme);
        EditText editText = (EditText) view.findViewById(R.id.contact);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                getActivity().startActivityForResult(intent, 1);

            }
        });


        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case (1):


                //ContentResolver cr = getContentResolver();
                Uri contactData = data.getData();
                Cursor c = getActivity().getContentResolver().query(contactData, phoneProjection, null, null, null);
                if (c.moveToFirst()) {
                    String numbers = c.getString(0);
                    Log.e("Hi", numbers);

                }
                break;
        }
    }
}

答案 1 :(得分:2)

请按照你说的那样试试#34;我需要离开加入第二个,其中checkcode1或checkcode2 喜欢 checkcode"

SELECT *
FROM Table1
INNER JOIN Table2 ON CONCAT(Table2.checkcode1,Table2.checkcode2) LIKE CONCAT('%', Table1.checkcode, '%')

修改

select * from Table1 as t1  
LEFT JOIN Table2 as t2 on t1.checkcode IN(t2.checkcode1 ,t2.checkcode2)

答案 2 :(得分:1)

您可以尝试以下查询:

SELECT t1.*, t2.*
FROM table1 t1 LEFT JOIN table2 t2 ON (t1.checkcode LIKE CONCAT('%', t2.checkcode1, '%') 
OR t1.checkcode LIKE CONCAT('%', t2.checkcode2, '%'));

如果您想要执行完全的字符串比较,可以将LIKE CONCAT('%', t2.checkcode2, '%')替换为= t2.checkcode2

答案 3 :(得分:0)

您也可以尝试这种方式来执行LEFT JOIN

Select * from Table1 as t1 LEFT JOIN Table2 as t2 on t1.checkcode IN (t2.checkcode1,t2.checkcode2);

SQL Fiddle

上查看