I have two different tables where I need to fetch the list of store ids from one table and then find the list of coupons for those store ids.
Currently,
SELECT `storename` FROM `stores` where `brandname` = 21
This will return something like
Store 1
Store 2
Store 3
Store 4
And I need to to run another query like
SELECT * FROM `coupons` where `storename` = {{All these stores}}
I can't use while loops because, the number of stores comes from first query can't be determined and the the output I want was not coming as expected while using while loop as I am trying to do something like
while(first query output get storename)
{
do query here
while(second query output get all coupons per store)
{
// All coupons display here.
}
}
This is making quite complicated as well, is there anyway that I can tweak my SQL query and get results easily?
Thanks
you can use this query:
SELECT * FROM `coupons`
where `storename` IN (
SELECT `storename` FROM `stores` where `brandname` = 21);
$query = 'SELECT t.storename, h.couponid AS couponsid, h.coupon AS couponvalue'
. ' FROM #__stores AS t'
. ' LEFT JOIN #__coupons AS h ON h.storename = t.storename'
. ' where `brandname` = 21'
. ' ORDER BY anything you like'
;
Related
I am a newbie in PHP/MySQL and this is my first question on stackoverflow, so please ignore any mistake if I have made any.
I am trying to get records from a table through this query.
$CId = $this->input->post('Child_id'); //child_id is the value from a textfield
$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
this query is returning an empty $r_detail. However when I query the same statement in PHPMyAdmin in localhost and change "$CID" to a number, I get the desired records.
Any Help will be much appreciated.
You have a space in INNER JOIN WHERE: '".$CId." ' should be '".$CId."'.
$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
has just string...you need to call some db function to get the data such as in code igniter may be
$this->db->query($r_detail);
I have 3 tables, and i have joined them together, which works fine, it pulls the information. One of the tables as an array within a column, on every row like:
["Pets","Schools","Shops"]
I need, while selecting, the query to pull out when a MATCH AGAINST a var. Here is my code:
$searchRefine = '';
foreach( $refineAmen as $key => $val) {
$searchRefine = $searchRefine . " MATCH(pa.Property_Amenities) AGAINST ('".$val."' IN BOOLEAN MODE) OR ";
}
The above takes each var from the array from the row / column, and adds it to a sub-query string.
$searchRefine = substr($searchRefine, 0, -3);
The above takes out the last 3 (or the word 'OR') at the end as its not needed
$detail = "SELECT p.*, pi.*, pa.* FROM tbl_property p LEFT join tbl_property_images pi on p.Property_Id = pi.Property_Id LEFT join tbl_property_amenities pa on pi.Property_Id = pa.Property_Id WHERE (p.Property_Postcode='" . $_POST['cust_id'] . "' OR p.Property_City Like '%" . $_POST['cust_id'] . "%') AND ( " . $searchRefine. " ) GROUP BY pi.Property_Id";
The above takes the sub strings and adds it to the final for firing. I do not get any errors.
The issue is, it does not pull the records with any of these key works within the row, just One. I have tried a number of combinations of AND or OR, so the query understands. But still no luck. Any someone look at this, and see if they can see what I have done wrong.
Thanks
You should normalize your database structure instead of storing multiple values in one column. This way you would not have to compute a sub-query string for fulltext search with MATCH...AGAINST.
Can you show your database structure?
Beware of SQL injection. Once your query is working you should alter it to escape client data oder use prepared statements.
I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}
i want to fetch duplicate data from the database but the problem is:
i have userids in an array like :
1235, 1235, 5468, 84321, 1235
i used implode and to make that array in string in implement into the database like:
"select * from tbl_name where userid in ('" . $implode_arr . "') limit 0, 10";
which is give me the result like 1235, 5468, 84321 but i want all the data, solution for this is simply run the query in the FOR LOOP or else
but i want same because i add the pagination within the query.
I don't want any code because its already working but the problem is to add pagination Please help to resolve the problem :(
It sounds like you want to join in the user data into this query. You can do that using a LEFT JOIN like this:
SELECT *
FROM tbl_name
LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid
WHERE userid IN (...)
LIMIT 0, 10
This is assuming your users are stored in the user table in the database_name database, and that the user table has an id field which matches up to the tbl_name field userid. If your fields or table names are different, just change them in this query. In PHP that would be:
"SELECT * FROM tbl_name LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid WHERE userid IN ('" . $implode_arr . "') LIMIT 0, 10"
Note that to connect two databases, both must be accessible by your same connected user.
Try this it would also work as expected
select * from tbl_name where FIND_IN_SET(user_id,'1235, 1235, 5468, 84321, 1235
') limit 1,10
Check this to remove duplicates
Is there any way to enumerate tables used in mysql query?
Lets say I have query :
SELECT * FROM db_people.people_facts pf
INNER JOIN db_system.connections sm ON sm.source_id = pf.object_id
INNER JOIN db_people.people p ON sm.target_id = p.object_id
ORDER BY pf.object_id DESC
And I want in return array:
$tables = array(
[0] => 'db_people.people_facts',
[1] => 'db_system.connections',
[2] => 'db_people.people',
);
Yes, you can get information about tables and columns that are part of a query result. This is called result set metadata.
The only PHP solution for MySQL result set metadata is to use the MySQLi extension and the mysqli_stmt::result_metadata() function.
$stmt = $mysqli->prepare("SELECT * FROM db_people.people_facts pf
INNER JOIN db_system.connections sm ON sm.source_id = pf.object_id
INNER JOIN db_people.people p ON sm.target_id = p.object_id
ORDER BY pf.object_id DESC");
$meta = $stmt->result_metadata();
$field1 = $meta->fetch_field();
echo "Table for field " . $field1->name . " is " . $field1->table . "\n";
You'll have to build the array of distinct tables used in the query yourself, by looping over the fields.
Depending on what you're using it for, MySQL's EXPLAIN could do the trick for you:
http://dev.mysql.com/doc/refman/5.0/en/explain.html
The solution marked as good will return only the result tables. But if you do the next query it will fail:
SELECT users.* FROM users, cats, dogs WHERE users.id = cats.user_id
Will return only users and not cats and dogs tables.
The best solution is find a good parser, another solution is using REGEX and EXPLAIN query (more info in the next link):
Get mysql tables in a query
But I think that another good solution is list all tables and search them inside the query, you can cache the list of tables.
EDIT: When searching for tables, better use a preg like:
// (`|'|"| )table_name(\1|$)
if(preg_match('/(`|\'|"| )table_name(\1|$)/i', $query))
// found
If not, it can return false positives with for example "table_name2", "table_name3"... table_name will return FOUND two times.