How to form the proper query - php

I am trying to form a query for MySQL where it gets all the info from multiple tables but only displays the ones where the "activity" = "Other". Right now it is displaying everyones info and I don't know the proper way to format the WHERE part of the query. I want it to access the jobSearch table, read the activity and only return the ones where the activity is "Other"
$query_student = " SELECT *
FROM student
JOIN major
ON student.studentID=major.studentID
JOIN jobSearch
ON major.studentID=jobSearch.studentID
WHERE jobSearch.activity == Other";

You SQL syntax is wrong, it should be:
SELECT * FROM table_name WHERE column = value
In your case:
SELECT * FROM student ... WHERE jobSearch.activity = 'Other'
For reference, check this good tutorial about SQL syntax: http://www.tutorialspoint.com/sql/sql-where-clause.htm

Your SQL syntax is OK is not wrong
SELECT *
FROM student
JOIN major ON student.studentID=major.studentID
JOIN jobSearch ON major.studentID=jobSearch.studentID
WHERE jobSearch.activity = 'Other';
If jobsearch.activity field is a varchar use single quotes around the word Other and use only one "=".
Also I recommend using alias and not using "Select *", you might run into a problem because you have the same field name in different tables, try to use something like this.
SELECT st.*, mj.field1, mj.field2, js.activity, js.field2
FROM student st
JOIN major mj ON st.studentID=mj.studentID
JOIN jobSearch js ON mj.studentID=js.studentID
WHERE js.activity = 'Other';

Related

I want to join two tables with a single query

I want to join student_image table with student_details table where
image_id = student_id
but Im stuck here, the query gives the student details, but now I want to add the student image to be displayed together with the student
Below is my query
$query = $this->db->get_where('student_detail',array('reg_no'=>$reg_no))->result_array();
Are you using CodeIgniter?
If you want to display student_image also you can do it like this:
$this->db->select('*');
$this->db->from('student_image a');
$this->db->join('student_details b', 'a.image_id=b.student_detail_id','inner');
$this->db->where('b.student_detail',$reg_no);
return $this->db->get();
or you can do like it this:
$query = "select * from student_image as a join student_details as b on a.image_id=b.student_detail_id where b.student_detail=?"
return $this->db->query($query ,array($reg_no));
I hope this solves your problem
Myself, and probably anyone else has absolutely no idea what that db class you're using is, so we cannot help you with that detail.
A query like this is very basic. A plain query would look somewhat like this:
SELECT *
FROM student_details, student_image
WHERE student_details.studentID = student_image.studentID
And that's it. Now you have to translate it into working with your db class...
I would recommend you learn basic mysql queries before you start using special pre-made classes. They make things a lot more complicated when you do not know what you want it to do yet.
-- The above query will get you the student details only if the row actually exists in both tables.
If you want it back even if it doesn't exist, you could use a LEFT JOIN, like so:
SELECT *
FROM student_details
LEFT JOIN student_image ON student_details.ID = student_image.ID
WHERE student_details.ID = 'myStudentID'
The above query would retrieve a student's results.

Problems with querying when a value is null

I am using php to query a database for one piece of information from each of 10 separate tables currently. The problem with using multiple queries is that it is extremely slow when accessing the web page that uses all of this information. I cannot seem to get all of the information back that I am wanting when one of the values does not exist due to the WHERE... statement.
For instance, my single queries are all in this format:
SELECT eval_id FROM eval WHERE user_id = $id;
My multiple table query looks like this:
SELECT eval_id,list_id,tab_id
FROM eval,list,tab
WHERE eval.user_id = $id
AND list.user_id = $id
AND tab.user_id = $id;
I tried to combine these queries into one large query, but when the user_id of one does not exist in the table, the comparison in the WHERE... statement screws up the entire query. Does anyone know the best way to retrieve all of this information?
Assume that the tables are "eval, list, and tab," and their id's are *_id respectively. What would be the best way to query this even if eval does not contain a result where the user_id = $id?
SELECT eval.eval_id, list.list_id
FROM user
JOIN eval ON eval.user_id = user.id
JOIN list ON list.user_id = user.id
WHERE user.id = $id
Hope it can help you.
Update: Just think about other solution:
SELECT eval_id as id, "eval" as table
FROM eval WHERE eval.user_id = $id
UNION
SELECT list_id as id, "list" as table
FROM list WHERE list.user_id = $id
You could use either of the following to your query in the WHERE statement:
AND TABLE.TABLE_id <> null //null
AND TABLE.TABLE_id <> 'null' //String null
AND TABLE.TABLE_id <> '' //empty String
Check your database to see what kind of empty value your id is returning and choose the addition that matches it.
Also, while LEFT JOINs may be better looking in a query, they are not always faster so make sure you test it before using.

Data from two tables with same column names

I have a table for users. But when a user makes any changes to their profile, I store them in a temp table until I approve them. The data then is copied over to the live table and deleted from the temp table.
What I want to achieve is that when viewing the data in the admin panel, or in the page where the user can double check before submitting, I want to write a single query that will allow me to fetch the data from both tables where the id in both equals $userid. Then I want to display them a table form, where old value appears in the left column and the new value appears in the right column.
I've found some sql solutions, but I'm not sure how to use them in php to echo the results as the columns in both have the same name.
Adding AS to a column name will allow you to alias it to a different name.
SELECT table1.name AS name1, table2.name AS name2, ...
FROM table1
INNER JOIN table2
ON ...
If you use the AS SQL keyword, you can rename a column just for that query's result.
SELECT
`member.uid`,
`member.column` AS `oldvalue`,
`edit.column` AS `newvalue`
FROM member, edit
WHERE
`member.uid` = $userId AND
`edit.uid` = $userId;
Something along those lines should work for you. Although SQL is not my strong point, so I'm pretty sure that this query would not work as is, even on a table with the correct fields and values.
Here is your required query.
Let suppose you have for example name field in two tables. Table one login and table 2 information. Now
SELECT login.name as LoginName , information.name InofName
FROM login left join information on information.user_id = login.id
Now you can use LoginName and InofName anywhere you need.
Use MySQL JOIN. And you can get all data from 2 tables in one mysql query.
SELECT * FROM `table1`
JOIN `table2` ON `table1`.`userid` = `table2`.`userid`
WHERE `table1`.`userid` = 1

How to perform a complex query using AS alias

First of all, I am new here and just learning sql, so bear with me.
I have a simple question. Let's say I have a table called voting with the following columns:
id, token(int), candidate(int), rank(int)
.. and I want to perform a query like:
SELECT *
FROM voting
WHERE rank > t1.rank
AND token = t1.token
.. where t1 is
SELECT rank,token
FROM voting
WHERE candidate = $mycandidate
How can I do this in a single statement using AS alias, or whatever is the simplest method?
Please note that final table created may have rows with different candidates than i have specified i.e the rank,token variables are initially chosen according to candidate but once chosen they may contain any candidate value with them.
Something like this should do, I believe:
select
v1.*
from
voting v1 inner join
voting v2
on v1.token = v2.token and
v2.candidate = $mycandidate and
v1.rank > v2.rank
EDIT changed SELECT * to SELECT v1.*

How can I get all field values from a query with JOINed tables?

I have this elementary query:
SELECT d.description, o.code FROM order_positions AS o
LEFT JOIN article_descriptions AS d ON (o.article_id = d.article_id)
WHERE o.order_id = 1
and I'm using MDB2 from PEAR to execute it and read the return values.
But somehow the result array always contains fields from the order_positions table only!, i.e. the result array looks like this
row[code] = 'abc123'
while I want it to look like this
row[description] = 'my description'
row[code] = 'abc123'
I already tried the following:
Vary the order of the fields, i.e. code first, then description.
Vary the order of the joined tables.
Used full table names instead of aliases.
Used the "MySQL join" instead (SELECT FROM table1, table2 WHERE table1.id = table2.id)
Used aliases with and without AS.
Some other facts:
Executing this query in MySQL Query Browser works fine, all fields are returned.
The order_positions table seems to be preferred, no matter what. When joining with additional tables I still only get fields from this table.
OK, I found the cause:
Fields with NULL values are not added to the array. In my test scenario description was in fact null and hence was not available in the array.
I'll still keep this (embarrassing) question, just in case someone else has this problem in the future.
Facepalm http://www.scienceblogs.de/frischer-wind/picard-facepalm-thumb-512x409.jpg
This should work:
SELECT d.description, o.code
FROM order_positions o, article_descriptions d
WHERE o.order_id = 1 AND d.article_id = o.article_id
Are you sure you're not using fetchOne() by mistake instead of fetchRow()?
Could you post your PHP code?
Another possibility is that in your code you missed the comma:
SELECT a b
is the same as
SELECT a AS b

Categories