Search the Community
Showing results for tags 'join'.
-
I've got two tables user table - id - username - fname - lname - group_id event Table - id - user_id - event_time - event_date - event ('Arrival','Departure','Break',etc..) My problem is getting all user by group and joining other table even date, but it should be base on 'event_date' I use `LEFT JOIN` and `LEFT OUTER JOIN` but because I have to specify the `event_date` not all user can be shown because some are absent. I made this SELECt * FROM user as u LEFT OUTER JOIN event as e ON u.id = e.user_id WHERE u.group_id = 6 AND ( e.event_date = '2016-07-05' AND e.event = 'Arrival' ) GROUP BY u.id but it only show the user who has an event on the date specified. I tried to make an VIEW table but it still has the condition base on event_date. Although I made this on PHP by condition but it takes time to load as I select event on every user. is there a way to get it using SQL? it should be like this:
-
I want to fetch the titles from the Courses table, but I only want the Course Title to return once when I join Events. Courses CID | CourseTitle 1 | Course A 2 | Course B 3 | Course C Events EID | CID | EventDate 1 | 1 | 2016-02-22 2 | 1 | 2016-02-23 3 | 2 | 2016-02-24 4 | 3 | 2016-02-25 5 | 3 | 2016-02-26 If I use a JOIN, SELECT Courses.CourseTitle FROM Courses LEFT JOIN Events on (Events.CID = Courses.CID) then I get Course A Course A Course B Course C Course C But what I want is Course A Course B Course C Because ultimately, I'm going to select an Event date range, and I want to see just the courses with the event date range. Thanks!
-
Hello all. I dont know how to go about this. I have a table (Transactions) that contains transactions of users. Another table (Confirmed) contains details of every confirmed user. I want to do a select statement that will display all the confirmed user with only the last of their transaction. But so far all it does is replicate the user and their date of transaction and that is not what i want. My intention is to get something like: Firstname Surname Date Registered Last Transaction andrews john 12-12-2014 10-10-2015 doe andy 12-12-2010 12-12-2014 But i'm getting something like: Firstname Surname Date Registered Last Transaction andrews john 12-12-2014 10-10-2015 andrews john 12-12-2014 10-11-2015 doe andy 12-12-2010 12-12-2014 doe andy 12-12-2010 01-12-2014 doe andy 12-12-2010 12-12-2013 Thanks $stm=$pdo->query("select * from confirmed left join transaction on confirmed.user_id = transaction.user_id where confirmed.status='confirmed' order by date"); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['firstname']; echo $row['surname']; echo $row['regDate']; echo $row['lastTrans']; }
-
Can't get my innerjoin to work with select sum groupby
alphamoment posted a topic in PHP Coding Help
Hello. I'm trying to get this piece of code finished but it's not going my way, if anyone could help me out that would be great. Here whats I'm trying to do: Table1 Table2 ---------------- --------------------------------- ID | | PlayerID | PlayerName | ---------------- -------------------------------- 1393 | | 1393 | Player1 | 2097 | | 2097 | Player2 | 3888 | | 3888 | Player3 | 3888 | | 4017 | Player4 | 3888 | --------------------------------- 4017 | 4017 | 4017 | ---------------- I Want to Count the entries in Table1 (3888 has 3 entries so it will display like "3888: 3") Then I want to join Table1 and Table2 using the ID so I can get the players name (3888=Player3 so it would display like Player3 : 3) Here's the code I'm using: <?php //connect to db $query = "SELECT * FROM Table1 INNER JOIN Table2 WHERE Table1.PlayerID = Table2.ID"; $query2 = "SELECT ID, SUM(ID=0) AS n0, SUM(ID=1) AS n1, COUNT(*) AS total FROM Table1 GROUP BY ID"; $result = mysql_query($query) or die($query."<br/><br/>".mysql_error()); $result2 = mysql_query($query2) or die($query2."<br/><br/>".mysql_error()); echo "<table border='1'> <tr> <th>PlayerName</th> <th>Entries</th> </tr>"; while($row2 = mysql_fetch_array($result2)) while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['ID'] . "</td>"; echo "<td>" . $row['PlayerName'] . "</td>"; echo "<td>" . $row2['Total'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($link); ?> If I use $query on its own it joins perfectly, If I use $query2 on its own, it displays the results exactly how I want them listed but with the ID instead of the PlayerName, I tried putting them both together as shown above but I can't get them to work together. What I want my end Result to be Player1 1 Player2 1 Player3 3 Player4 3 How it keeps coming out; 1393 1 2097 1 3888 3 4017 3 Can anyone see where I'm going wrong? Thank you!! -
I have a question about how I would structure a query. I have 2 tables. Store store_id -- primary key zip_code Merchandise item_id -- primary key item_name description cost storeID -- foreign key that references the store_id from the store. I am using InnoDB. I want the user to be able to input 1-5 choices that are 1 word apiece and it would cross reference the decription and tell me the store that has them both. For instance, choice 1 = clock, choice 2 = paper, and choice 3 = food. It would query a result that would give me the stores that have items that match the description of them all. For instance, it would return Wal - Mart based on this query because it would be the only store that had an item to match each description. Any help is much appreciated. Thanks!
-
Hi all. I have two tables where the username is what they have in common. i want to perform a join for both tables but i'm having problems with mysql joins. //to get the desire result individually i did //table one $stmt = $pdo->query("SELECT * FROM tableone WHERE username = '$_GET[id]'"); $row = $stmt->fetch(PDO::FETCH_ASSOC); $credit_score = $row['credit_score']; $acct_num = $row['acct_num']; $acct_name = ucwords($row['surname']) ." ". ucwords($row['firstname']); $username = $row['username']; if($credit_score ==3){ $bill_limits = 2000; }elseif($credit_score ==2){ $bill_limits = 1000; }elseif($credit_score ==1){ $bill_limits = 500; } //table two $stmt=$pdo->query("SELECT SUM(amt) as bill FROM tabletwo WHERE username = '$_GET[id]' AND relationship = 'PARENT'"); $row = $stmt->fetch(PDO::FETCH_ASSOC); $bill = $row['bill']; $service_charge_for_limits = '0.05' * $bill; $tax_rate_for_limits = '0.13' * $service_charge_for_limits; $bill_sum = $tax_rate_for_limits + $service_charge_for_limits + $bill; Approved Bill Limits = $<?php echo number_format($bill_limits,2); ?> <br> Bill Limits Used = $<?php echo number_format($bill_sum,2); ?> <br> <?php $available_limits = $bill_limits - $bill_sum; ?> Bill Limits Available = $<?php echo number_format($available_limits,2); ?> The above gives me the correct result, but now i have another page where i want to all the clients and their corresponding available limits, used limits and approve limits form table two and other information from table one On the page i have $stmt = $pdo->prepare("SELECT * FROM tableone WHERE status = 'COMPLETED' ORDER BY id DESC LIMIT $start, $limit"); $stmt->execute(); $num_rows = $stmt->rowCount(); echo "<table width='100%' class='table-responsive table-hover table-condensed table-striped'>"; echo "<tr> <th bgcolor='#444444' align='center'><font color='#fff'>Account Number</th> <th bgcolor='#444444' align='center'><font color='#fff'>Subscriber's Name</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Username</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Limits ($)</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>View Profile</font></th> <th bgcolor='#444444' align='center'><font color='#fff'>Delete Account</font></th> </tr>"; // keeps getting the next row until there are no more to get while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // Print out the contents of each row into a table echo "<tr><td>"; echo $row['acct_num']; echo "</td><td>"; echo ucwords($row['surname']." ". $row['firstname']); echo "</td><td>"; echo $row['username']; echo "</td><td>"; $credit_score = $row['credit_score']; if($credit_score ==3){ $bill_limits = 2000; }elseif($credit_score ==2){ $bill_limits = 1000; }elseif($credit_score ==1){ $bill_limits = 500; } echo number_format($bill_limits, 2); echo "</td><td>"; echo "<a href='view-client-profile.php?id={$row['username']}'>view more</a>"; echo "</td><td>"; echo "<a href='delete-account.php?id={$row['username']}'>Delete Account</a>"; echo "</td></tr>"; //echo "</td><td>"; //echo "<a href='settle.php?id={$row['acct_num']}'>Points</a>"; } echo "</table>"; How ca i join tableone and tabletwo (plus sum)
-
I have data similar to below. I am doing a MySQL query and doing a JOIN based on instructor name. I am echoing classes and linking the instructor name to another page with their BIO. All is working great, however I want to use the ID's for something else. How do I differentiate the ID between the Instructors table and the Classes Table without changing the column name in the database? For instance, I want to echo the Instructor ID and then echo the Classes ID, but they are both the same column name in the database and since they are joined, how will that work? Instructors: ID | Instructor | Title | Bio | 1 | Bob Smith | Chef | bob smith is a chef with... | 2 | Jane Doe | Professor | Jane doe is an instructor that... | Classes: ID | Instructor | Class Title | Class Description | 4 | Bob Smith | Baking | this is a baking class where you learn.... | 5 | Jane Doe | Food Safety | Food safety is very important... |
- 2 replies
-
- join
- multiple columns
-
(and 2 more)
Tagged with:
-
I have two tables 'book' and 'category'. They look like the following in phpmyadmin; book id title author category isbn ---- ------- ---------- ---------- ------- 1 Treasure Chest Jim Jones 1 14252637 2 Pirates Boat Sue Smith 2 88447737 3 Adventure Land Harry Jo 3 01918273 4 Winter Week Sam Dill 3 00999337 5 The Twite Roald Dahl Fiction 87873366 category id cat_name ---- ------- 1 Horror 2 Kids 3 Fiction 4 Science Users have the option of adding books into the library via an online form, or via a Google Booka api method (user enters isbn, searches, is presented with book info and then clicks 'add to library', done.). This is handled via ajax. The online form works fine, and successfully adds the book info. However my problem is with the Google Books method, it successfully adds the data to the db however the category column is in text format (i.e 'Juvenile Science' or 'Scary Fiction') as opposed to the manual form which adds categories as 1, 2 or 3 (1 =Horror, 2 = Kids, 3 = Fiction). Is there any way I can add the Google Book category data to my table and convert it to an integer or similar? Not sure what I need to do. Suggestions appreciated! Should I add the Google entries to another table (i.e googleCategory)? My HTML only outputs the numbered category entries and ignored the text format entries. my php $sql = "SELECT b.id, b.title, b.author, b.isbn, b.publicationYear, c.cat_name FROM book AS b INNER JOIN category AS c ON b.category = c.id WHERE status != 'Archive' ORDER BY id DESC LIMIT $startrow, 15 "; $res = $conn->query($sql) or trigger_error($conn->error."[$sql]"); while($row = $res->fetch_array()) { echo '<tbody>'; echo '<tr>'; echo '<td>' . $row['id'] . '</td>'; echo '<td>' . $row['title'] . '</td>'; echo '<td>' . $row['author'] . '</td>'; echo '<td>' . $row['cat_name'] . '</td>'; echo '<td>' . $row['isbn'] . '</td>'; echo '<td>' . $row['publicationYear'] . '</td>'; echo '</tr>'; echo '</tbody>'; }; Apologies if this is all a bit confusing I am very new to php and mysql. Thanks, J
-
I am creating a library app for personal development and would like to further my knowledge of MySql. I currently have two tables 'book' and 'category' book id title author category isbn ---- ------- ---------- ---------- ------- 1 Treasure Chest Jim Jones 1 14252637 2 Pirates Boat Sue Smith 2 88447737 3 Adventure Land Harry Jo 3 01918273 4 Winter Week Sam Dill 3 00999337 category id cat_name ---- ------- 1 Horror 2 Kids 3 Fiction 4 Science I am doing a simple search where I want to display all books (select * from book) and I would like to display all the books with their corresponding categories. This works but displays the category number instead of the category name. How can I alter these tables in such a way that the cat_name and category are joined? I tried to run a command in phpmyadmin as below however it returned an error; ALTER TABLE book ADD FOREIGN KEY (category) REFERENCES category(cat_name); error #1452 - Cannot add or update a child row: a foreign key constraint fails (`sslib`.`#sql-1ab4_1dae`, CONSTRAINT `#sql-1ab4_1dae_ibfk_1` FOREIGN KEY (`category`) REFERENCES `category` (`cat_name`)) I have been looking at foreign keys and indexes however I can't seem to make any sense of them. I am quite new to this so any help is much appreciated. Regards, J
-
Hello guys. Thanks a lot for any help with this. My problem is that I'm trying to use MAX to get the last item in the portafolio table. This is my query: $result = $db->prepare( "SELECT * FROM portafolio INNER JOIN imagenes ON imagenes.work = portafolio.idp WHERE work = ? ORDER BY iid DESC); $result->execute(array($_GET['work'])); The main idea is not use $_GET['work'], because i want to display the last work (with their respective images) in my portafolio in the main page, so im not passing any variable by url.
-
I am somewhat of a newbie and think this is a simple fix, but I have been having problems and can't seem to figure it out. I am trying to JOIN two tables, but am not getting the results I would like. I am getting the correct question number displayed whenever I try different instances, but it always defaults to the "DTCAP" question (q_code). I have included the snippet of code and how the table structure looks. Any help would be greatly appreciated! ------------------------------------------------------------------------------------- //Testing to ensure that the $_SESSION['code'] is DTCAP, CNROW, or MONFW after user chooses option echo $_SESSION['code']; $query_question=mysql_query("SELECT * FROM adventure_questions q INNER JOIN users_adventures u ON q.q_number = u.ua_question WHERE u.ua_username = '$_SESSION[username]' AND u.ua_code='$_SESSION '"); $question_info=mysql_fetch_array($query_question); echo $question_info['q_number'].". ".$question_info['question']; ------------------------------------------------------------------------------------- adventure_questions q_id q_code q_number question 1 DTCAP 1 DTCAP question 1 2 DTCAP 2 DTCAP question 2 26 CNROW 1 CNROW question 1 27 CNROW 2 CNROW question 2 51 MONFW 1 MONFW question 1 52 MONFW 2 MONFW question 2 users_adventures ua_id ua_username ua_code ua_question ua_score 1 kjb31ca DTCAP 1 0 2 kjb31ca CNROW 2 10 3 kjb31ca MONFW 1 0
-
Hello all Have a problem with some query and i'll explain it now... I attached image file with tables which i have SELECT car.id, car.model, books.id, books.car_id, books.start_date, books.end_date FROM car LEFT JOIN books ON books.car_id = car.id WHERE books.car_id IS NULL OR books.start_date NOT BETWEEN '" . $_POST['start'] . "' AND '" . $_POST['end'] . "' AND books.end_date NOT BETWEEN '" . $_POST['start'] . "' AND '" . $_POST['end'] . "' GROUP BY books.car_id"; when car with id 1 is booked 1 time, car doesnt appears if book date range is matches to users choosen date range, but when car with id 1 is booked 3 times it appears 2 time becouse time range matched only one record of book table. i want that if time rage is matched even for one books record, dont show this car at all.. Please help with this and tanks you p.s. Sorry for my English
-
Hello. I' have a Table in MySQL That stores data (name/email/time) of when a person last run X script. I'm trying to pull that information for each user unique to their account to display so they know that they've already ran that script today How it works. Run script > Create's Row storing the data > MySQL Events deletes row after 24 hours. My code to display notification if they have already ran it; $sql = 'SELECT a.name, a.time FROM timecheck a, users b WHERE a.name = b.name'; mysql_select_db('My_DB'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Account: {$row['name']} <br> ". "Last Time Run: {$row['time']} GMT -1<br> "; } echo "It seems you have done this already today!"; ?> Now my problem is. It's displaying every row to every user. I want it to only show the user their row... What I've tried. Creating a session variable "$sessionID" $sql = 'SELECT a.name, a.time FROM timecheck a, users b WHERE a.name = b.name AND a.name=$sessionID"'; But I'm not getting any lucky. All help is appreciated, thank you in advance.
-
Hello all! I'm makeing car booking module and have one problem. Explaining... There is tree joined tables "books", "car" and "cat". When i joining this three table it retrieves ids from table "car", but i want ids from "books" what to do? Can you help? Thanks <?php if($db->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } $query = " SELECT * FROM books LEFT JOIN car ON books.car_id = car.id LEFT JOIN cat ON books.cat_id = cat.id WHERE books.owner = '$owner'"; $result = mysqli_query($db,$query) or die("Error: ".mysqli_error($db)); $myrow = mysqli_fetch_array($result, MYSQLI_BOTH); if(mysqli_num_rows($result) > 0){ if($db->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } do { printf ('<tr> <td>'.$myrow["id"].'</td> <td>'.$myrow["model"].'</td> <td>'.$myrow["cat_name"].'</td> <td>'.$myrow["name"].'</td> <td>'.$myrow["surname"].'</td> <td>'.$myrow["country"].'</td> <td>'.$myrow["phone"].'</td> <td>'.$myrow["notes"].'</td> <td>'.$myrow["start_date"].'</td> <td>'.$myrow["end_date"].'</td> <td>'.$myrow["owner"].'</td> <td>'.$myrow["site"].'</td> <td><a href="delete.php?id='.$myrow["id"].'">Delete</a></td> </tr>'); } while ($myrow = mysqli_fetch_array($result)); } else{ echo '<p align="center" style="margin-top:100px;">There are no records...</p>'; } ?>
-
Hello all This code below works but doesn't filter records by owner. Please help. thanks SELECT * FROM books LEFT JOIN car ON books.car_id = car.id LEFT JOIN cat ON books.cat_id = cat.id WHERE books.owner = '$owner'
-
Hi to everyone and sorry for my bad english... there is a table, ServErog (service) wich is releaded to other 4 tables ServA, ServB, ServC, ServD (they are different non uniformable services) with two key, servtype (type of service) and type_id (numeric id from one of the 4 service table) Structure (simplyficaded): ServErog mysql> select * from ServErog +----+-------+----------+------+ | idSE | servtype | type_id | +----+-------+----------+------+ | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 4 | 1 | | 4 | 3 | 1 | | 5 | 1 | 2 | +----+-------+----------+-------+ ServA mysql> select * from ServA +----+-------+----------+------+ | idSA | service_code | type | |+----+-------+----------+------+ | 1 | codice bla | 1 | | 2 | codice ecc | 1 | | 3 | bla bla | 1 | +----+-------+----------+------+ ServB mysql> select * from ServB +----+-------+----------+------+ | idSB | service_code | type | +----+-------+----------+------+ | 1 | codice bla | 2 | | 2 | codice ecc | 2 | | 3 | bla bla | 2 | +----+-------+----------+------+ ServC mysql> select * from ServC +----+-------+----------+------+ | idSC | service_code | type | +----+-------+----------+------+ | 1 | codice bla | 3 | | 2 | codice ecc | 3 | | 3 | bla bla | 3 | +----+-------+----------+------+ ServD mysql> select * from ServD +----+-------+----------+------+ | idSA | service_code | type | +----+-------+----------+------+ | 1 | codice bla | 4 | | 2 | codice ecc | 4 | | 3 | bla bla | 4 | +----+-------+----------+------+ Left Join Select ServErog.idSE, ServErog.servtype, ServErog.typeid, ServA.idSA, ServA.type, ServB.idSB, ServB.type, Serv.idSA, Serv.type, ServD.idSA, ServD.type From ServErog Left Join ServA On ServErog.servtype = ServA.type And ServA.idSA = ServErog.typeid Left Join ServB On ServErog.servtype = ServB.type And ServB.idSB = ServErog.typeid Left Join ServC On ServErog.servtype = ServC.type And ServC.idSC = ServErog.typeid Left Join ServD On ServErog.servtype = ServD.type And ServD.idSD = ServErog.typeid Order By ServErog.idSE +----+-------+----------+------+------+------+---------+ | idSE | servtype | type_id | idSA | idSB | idSC | idSD | +----+-------+----------+------+------+------+---------+ | 1 | 1 | 1 | 1 | null | null | null | | 2 | 2 | 1 | null | 1 | null | null | | 3 | 4 | 1 | null | null | null | 1 | | 4 | 3 | 1 | null | null | 1 | null | | 5 | 1 | 2 | 2 | null | null | null | +----+-------+----------+------+------+ This retur all records releaded with ServErog. Perfect! Now I need to show all record from ServA, ServB, ServC, ServD NOT PRESENT in ServErog. It's like an inverse of the precedent Join. I've tried with right join, with idSE is null but without result This is what I looking for this example: +----+-------+----------+------+ | idSA | idSB | idSC | idSD| +----+-------+----------+------+ | 3 | null | null | null | | null | 2 | null | null | | null | 3 | null | null | | null | null | 2 | null | | null | null | 3 | null | | null | null | null | 2 | | null | null | null | 3 | +----+-------+----------+------+
-
Two tables, pull last record of table B that references table A
bsamson posted a topic in MySQL Help
I thought I had this issue figured out last night with the help from this forum, but turns out it still isn't working as expected. I have two tables: Table: sapImport id invoiceNo invoicedAtID invoicedAtName soldOn soldBy customer 1 CICIN123 3 Cicero 1384832632 brian john smith 2 DESTIN12 5 Destiny 1384832632 brian Henry Will 3 VESTIN32 3 Cicero 1384832632 jason Peter Jenn Table: conStatus id store record statusCode 34 3 1 0 35 5 3 0 39 3 1 15 I do have more rows than this, but i'm just trying to give an idea ... I currently have the following query: SELECT * FROM sapImport si INNER JOIN conStatus cs ON si.id = cs.record INNER JOIN ( SELECT record, MAX(id) as id FROM conStatus GROUP BY record ) mx ON cs.record = mx.record AND cs.record = mx.id WHERE cs.store='$storeID' AND cs.statusCode < '998' Basically, the table sapImport contains customer information and the conStatus table contains all interactions with a record in the sapImport table. The 'id' row in sapImport is the primary key and is auto-incremented. The 'record' row in conStatus references the 'id' row from sapImport. I need a query that pulls the LAST record (from conStatus) for a particular customer (from sapImport) where the store=x and the statusCode is less than 998. I should only get ONE result set with this. Any help will be GREATLY appreciated! Thanks in advance! -
Hi! I have 2 tables (See attached image). I want to select all(') from the table variables, but I only want to get data where variables.ID doesn't exist in table translations.ID. okey! So if the variables-ID does not exist in the table-translation:Variable, den I want to get it. Also, there must have to be a where statement so I can choose too fetch variables with language (id) 3, or another integer. I want this because I want to select all variables which hasn't been used in the translation table. I have tried with innerjoin... and actually I have never used joins before, never had too. But now I think I have to, but my innerjoin didn't worked. And because of my understanding in joins is small, I also tried left and right join but I din't get it too work. It would by my knowledge be something like this. SELECT variables.* FROM variables INNER JOIN translations ON variables.id != translations.id WHERE language = 3 But no.. I only get all variables even if the variable ID is in the translation.variable table. Thanks in advance! I guess this is simple for you guys.
-
I am having trouble writing exactly 4 queries in mysql. Here is the view I am using for queries: http://pastie.org/8403299 Here is the Raw Data you can check http://goo.gl/z7Vv9X which you can check. What is needed: 1) Gained students are those who exist in the selected / filtered month and don't exist in the previous month. 2) Lost students are those who exist in the previous month of the selected / filtered month and don't exist in the selected / filtered month. 3) Get a list of all lost students since the start of the center till now(). 4) Get a list of all gained students since the start of center till now. I am currently stuck with query 1) (Gained students are those who exist in the selected / filtered month and don't exist in the previous month.) I have written it like that (see just below), but I get the same number of rows back if I haven't filtered anything... uff. SELECT * FROM lessons_master_001 my1 WHERE NOT EXISTS ( SELECT 0 FROM lessons_master_001 my2 WHERE my1.student_id = my2.`student_id` AND my1.teacher_id = my2.teacher_id AND my1.`student_payment_id`= my2.`student_payment_id`AND CONCAT(CAST(MONTH(DATE_ADD(my1.Lesson_Booking_Date, INTERVAL -1 MONTH))AS CHAR(20)),CAST(YEAR(DATE_ADD(my1.Lesson_Booking_Date, INTERVAL -1 MONTH))AS CHAR(20))) = CONCAT(CAST(MONTH(my2.`Lesson_Booking_Date`)AS CHAR(20)),CAST(YEAR(my2.`Lesson_Booking_Date`)AS CHAR(20))) ) My logic is like this so I take everything from the view lessons_master_001 and give alias my1 and in the NOT EXISTS clause I am giving to the same dataset alias my2, then join those ID's that are also used in view lessons_master_001 and then try to connect previous month from data set my1 with current month from data set my2. I am using DATE_ADD function to subtract month from current date and practically get date - 1 month. I would really appreciate any help you will provide, cause I lost 2 days already on it with no progress in front. Thank you in advance.
-
Below is my query: <?php if (isset($_POST['search_all_submit'])){ $search_all = strtolower($_POST['search_all']); echo "<table id='qbook'>"; echo "<tr>"; echo "<td> CID </td>"; echo "<td> Company </td>"; echo "<td> Property </td>"; echo "<td> Contact </td>"; echo "</tr>"; $sql = " SELECT contract.*, customer.*, contact.* FROM customer INNER JOIN contract ON customer.customer_id = contract.customer_id INNER JOIN contact ON customer.customer_id = contact.customer_id WHERE customer.company_name like '%".$search_all."%' or customer.billing_address like '%".$search_all."%' or contract.prop_name like '%".$search_all."%' or contract.prop_address like '%".$search_all."%' or contact.contact_fname like '%".$search_all."%' or contact.contact_lname like '%".$search_all."%' "; $results = mysql_query($sql)or die(mysql_error()); while ($row = mysql_fetch_array($results)){ $company_name = implode('<span class="high">'.$search_all.'</span>',explode($search_all,strtolower($row['company_name']))); $billing_address = implode('<span class="high">'.$search_all.'</span>',explode($search_all,strtolower($row['billing_address']))); $prop_name = implode('<span class="high">'.$search_all.'</span>',explode($search_all,strtolower($row['prop_name']))); $prop_address = implode('<span class="high">'.$search_all.'</span>',explode($search_all,strtolower($row['prop_address']))); $fname = implode('<span class="high">'.$search_all.'</span>',explode($search_all,strtolower($row['contact_fname']))); $lname = implode('<span class="high">'.$search_all.'</span>',explode($search_all,strtolower($row['contact_lname']))); $CID = $row['CID']; echo "<tr>"; echo "<td> $CID </td>"; echo "<td> $company_name <br /> $billing_address </td>"; echo "<td> $prop_name <br /> $prop_address </td>"; echo "<td> $fname $lname</td>"; echo "</tr>"; } echo "</table>"; } ?> The query above gives me results like: 10008 | jw property management | creekside crossing | mike pudelek | 4816 green bay rd | 9219 66th ave | 10008 | jw property management | creekside crossing | sam johnson | 4816 green bay rd | 9219 66th ave | 10008 | jw property management | creekside crossing | dean zierk | 4816 green bay rd | 9219 66th ave | What I would like to see is: 10008 | jw property management | creekside crossing | dean zierk | 4816 green bay rd | 9219 66th ave | mike pudelek | sam johnson I am pretty sure that I need to use some type of GROUP CONCAT and possibly a GROUP BY. However all of my attemps have failed. Any help would be appreciated.
- 2 replies
-
- concat
- mysql join
-
(and 3 more)
Tagged with:
-
Hello, i have a table i have to fill out with info regarding other tables, is a join possible or do i have to make 2 queries? This is what i have right now. $date = date("Y-m-d H:i:s"); $sql = "INSERT INTO tblpaqueteria ( sender_id, reciever_id, AddTime, Estatus, ubicacion, tipo,slocalidad_id,rlocalidad_id ) VALUES ( '{$_POST['id_send']}', '{$_POST['id_rec']}', '{$date}', '0' , '0', '{$_POST['tipo_paq']}',0,0 )"; $res = mysql_query($sql,$this->conn); return $sql; What i need now is to change some of my insert into dynamic ones, i have to enter into "slocalidad_id" and into "ubicacion" the "id" of a table called localidad, and this id is being referenced from a table called "usuarios" (users) where "$_POST['id_send']" where localidad_id marks the id i need to insert into tblpaqueteria. I am not sure if I explained myself correctly so ill try and make an example. usuarios So for my sql above, without joins i would be receiving from POST id_send = 2 and from id_rec 11 so my query should insert this $sql = "INSERT INTO tblpaqueteria ( sender_id, reciever_id, AddTime, Estatus, ubicacion, tipo,slocalidad_id,rlocalidad_id ) VALUES ( '{$_POST['id_send']}', '{$_POST['id_rec']}', '{$date}', '0' , '2', '{$_POST['tipo_paq']}',2,4 )"; notice the numbers "2" and "4" being inserted, those are the ones i don't know how to enter dynamically, i think its a join, but i don't know how to use them in an insert. Thanks a lot
-
I'm designing a website for a wine wholesaler that needs to be able to update and display their product catalog in a certain specific way. The site in development is at www.metrocellars.com/new/ Let me first begin by outlining the database tables in use: location - a table of 6 records, the broader breakdown of geographic location (Brazil, California, etc.) These rows are used in the navigation menu, and each location has many "regions" referencing them. region - the more specific area of origin of each product (wine). Each "Region" references one of the 6 broader "Locations". product - The meat of the db, each Product record references a Producer/Winery (PID), a specific Region (RID - which also references a broader Location), and a specific Varietal (VID - Wine type/color). The left part of the image below shows part of the Product table. winery - This table holds records of each Winery/Producer referenced by PID in Product table. varietals - This table lists each type of wine, (Pinot, Merlot, etc) referenced by VID in the Product table. On the right side of the above image, I included a visual of the relevant tables with FK relation lines. I haven't figured out which ON DELETE/UPDATE to use, as I got errors a couple times from child rows as I was assigning indexes/keys. I'm a little rusty with the SQL at the moment. Using this model, I need to be able to output the data to a wine list page, but I am having problems putting together the right queries and loops to list the data in the requested format. Here is an example of what the page content should look like when the 'region' California (LID = 2) is clicked on the nav menu. California Slo Down Wines http://www.slodownwines.com/ Broken Dreams Sexual Chocolate Central Coast Jackhammer http://jackhammerwine.com Pinot Noir Happy Canyon of Santa Barbara Cimarone Winery http://www.cimarone.com/ 3CV Bank 3CV Cilla’s Blend Le Clos Secret Gran Premio 3CV Estate Sauvignon Blanc Dragonette Cellars http://dragonettecellars.com/ GMS Rose Sauvignon Blanc Happy Canyon Vineyards http://happycanyonvineyard.com/ Ten Goal Merlot http://happycanyonvineyard.com/ Piocho Margerum Wine Company Sybarite Sauvignon Blanc Paso Robles Spaceman Vineyards Reserve Airspace Santa Barbara County Ampelos Cellars Syrache - Syrah & Grenache Margerum Wine Company http://www.margerumwinecompany.com/ Chenin Blanc M5 Riesling Uber Reserve Tercero http://tercerowines.com/ Grenache Grenache Blanc The Climb Santa Lucia Highlands Jackhammer http://jackhammerwine.com Chardonnay Santa Maria Tyler Winery Bien Nacido Pinot Noir Sta Rita Hills Ampelos Cellars http://ampeloscellars.com/ Pinot Noir Lambda Reserve Rho Reserve Viognier Dragonette Cellars http://dragonettecellars.com/ In the above list, each heading is a record of each "Region" with the same LID as California in the Location table. LID = 2, so I need to list each Region within California, and within each of those listings, list each Wine that has the same RID as that Region, but grouped by their respective Wineries. Basically, there are a few Wineries that have products (child rows I believe) with differing Regions of origin. So, there are products that can have the same PID, but different RID. You can get an idea of the format from the above example. My problem is, is how would I nest the loops and queries, and what joins would be necessary? Any and all help is a godsend. This has been quite a headache.
-
I have 4 functions which are changing four different parameters. But when i change them one after another every parameter is changing without including 3 left. How can i change that? Here is the code: <script text="text/javascript"> $(function(){ $('#T1Slider').slider({ change: function(){ var T1 = $(this).slider('option','value') $('#lissajousOutput').attr('src', 'lissajous.php?T1='+T1) } }); }); </script> <script text="text/javascript"> $(function(){ $('#T2Slider').slider({ change: function(){ var T2 = $(this).slider('option','value') $('#lissajousOutput').attr('src', 'lissajous.php?T2='+T2) } }); }); </script> <script text="text/javascript"> $(function(){ $('#a1Slider').slider({ change: function(){ var a1 = $(this).slider('option','value') $('#lissajousOutput').attr('src', 'lissajous.php?a1='+a1) } }); }); </script> <script text="text/javascript"> $(function(){ $('#a2Slider').slider({ change: function(){ var a2 = $(this).slider('option','value') $('#lissajousOutput').attr('src', 'lissajous.php?a2='+a2) } }); }); </script> <link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> </head> <center><img src="lissajous.php" id="lissajousOutput"></center> </br></br> <center>T1<div name="T1" style="width: 800px; " id="T1Slider"></div></center> <br> <center>T2<div name="T2" style="width: 800px; " id="T2Slider"></div></center> <br> <center>a1<div name="a1" style="width: 800px; " id="a1Slider"></div></center> <br> <center>a2<div name="a2" style="width: 800px; " id="a2Slider"></div></center>
-
I'm stumped on how to get this join to work: Statement: SELECT * FROM votes WHERE NOT EXISTS (`votes`.`poll_id` = `user_votes`.`vote_poll_id` AND `user_votes`.`user_id`='1') limit 1 order by rand() Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`votes`.`poll_id` = `user_votes`.`vote_poll_id`) limit 1 order by rand()' at line 3 Possibly, but doubt it: the table is completely blank. Goal: Find all the entries that the user hasn't voted on as of yet, then submit them randomly to the user.
- 19 replies
-
- not exists
- rand()
-
(and 1 more)
Tagged with:
-
please help i have assignment to selecting tables by joining them.. how do i use join, or inner join? is there another option selecting 3 tables by using foreign key? Here's the table this one is user table here is article category and this is content of article i was willing to choosing article_news table = article_id, category_article_id, user_type_id, user_id, judul(title), artikel, photo, tag, tanggal tcategory_article = category_article_id, category_article tuser = user_type_id, firstname, lastname thank you
- 3 replies
-
- inner join
- join
-
(and 3 more)
Tagged with: