SQL JOIN:从具有匹配ID的另一个表中选择记录

时间:2016-02-05 14:46:16

标签: mysql sql join

我无法构建正确的SQL JOIN语句来从另一个表中选择一些记录。

--Table Product:
ID
Name
CatID1
CatID2

--Table Category:
CatID
CategoryName

Product.CatID1Product.CatID2Category.CatID

引用

所以我真的想选择Product字段并将Product.CatID1Product.CatID2替换为Category.CategoryName(对于Product.CatID1)和Category.CategoryName(对于Product.CatID2 SELECT Product.ID, Product.Name, Category.CategoryName as Product.CatID1, Category.CategoryName as Product.CatID2 from product, categories; )。

这显然不起作用,但解释了我的需要:

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("picturePath", picturePath).commit();
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.User);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }

    }

2 个答案:

答案 0 :(得分:2)

您只需要一张双LEFT JOINcategories表:

SELECT p.ID, p.Name, 
       c1.CategoryName as CatID1, 
       c2.CategoryName as CatID2 
from product AS p 
LEFT JOIN categories AS c1 ON p.CatID1 = c1.CatID
LEFT JOIN categories AS c2 ON p.CatID2 = c2.CatID

如果CatID1CatID2不匹配,则SELECT子句中的相应字段将为NULL

答案 1 :(得分:0)

SELECT Product.ID, 
Product.Name, 
C1.CategoryName as Product.CatID1, 
C2.CategoryName as Product.CatID2 
FROM Product JOIN  Category C1 ON C1.CatID = CatID1
JOIN  Category C2 ON C2.CatID = CatID2 ;

两次使用类别表。

如果您将来决定产品可以分为3类,该怎么办?实际上,您应该有一个连接表,并从Product中删除重复信息。