Search code examples
mysqlmysql-error-1292

Should be simple? MySQL query: substitute ID (int) in one table with title (varchar) from other table


I have a question which seems very basic to me, but cannot find the answer to it. I have two tables: A & B. Table A has a column with id-s (int), table B connects those id-s with descriptions (varchar.) I want to do a query on table A, where I replace the id-s with the descriptions from table B (one-one relation). I currently have this query:

select tableA.* from tableA join tableB on (tableA.id=tableB.description);

This should do the job, apart from that I get Warning 1292 : "Truncated incorrect DOUBLE value".

I understand what it means, the two data types don't match. But then how to make it work? I am sure this must be a simple fix and that what I ask for is being used all the time (e.g. replace ISBN with book title, etc.)...

Any help would be much appreciated!

Edit upon request

Sorry people, I thought it was not ambiguous... Db structure:

mysql> describe tasks;
+----------+-----------------------+------+-----+---------+----------------+
| Field    | Type                  | Null | Key | Default | Extra          |
+----------+-----------------------+------+-----+---------+----------------+
| tid      | int(10) unsigned      | NO   | PRI | NULL    | auto_increment |
| pid      | int(10) unsigned      | YES  |     | NULL    |                |
| username | varchar(15)           | YES  |     | NULL    |                |
| task     | varchar(1000)         | NO   |     | NULL    |                |
+----------+-----------------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql> describe projects;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| pid   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| title | varchar(200)     | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

I want to "select * from tasks", where every pid is replaced with the corresponding title from table projects in the same query.

Hope it's now clearer...


Solution

  • You can simply use the following query to join the contents of both tables getting all entries from the task table even if they have no project attached:

    SELECT t.tid, t.username, t.task, p.title 
    FROM tasks t 
    LEFT JOIN projects p ON t.pid = p.pid;
    

    If you just want tasks with an attached project use this query instead:

    SELECT t.tid, t.username, t.task, p.title 
    FROM tasks t 
    JOIN projects p ON t.pid = p.pid;